import { Request, Response } from 'express';
import { PostService } from '../services/PostService';

export class PostController {
  private postService: PostService;

  constructor() {
    this.postService = new PostService();
  }

  // 创建文章
  createPost = async (req: Request, res: Response): Promise<void> => {
    try {
      const { title, content, summary, authorId } = req.body;
      
      if (!authorId) {
        res.status(400).json({ error: '作者ID不能为空' });
        return;
      }

      const post = await this.postService.createPost({
        title,
        content,
        summary,
      }, authorId);

      res.status(201).json({
        message: '文章创建成功',
        post,
      });
    } catch (error) {
      res.status(400).json({ error: error instanceof Error ? error.message : '创建文章失败' });
    }
  };

  // 获取文章详情
  getPostById = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const post = await this.postService.findPostById(parseInt(id));
      
      if (!post) {
        res.status(404).json({ error: '文章不存在' });
        return;
      }

      res.json({ post });
    } catch (error) {
      res.status(500).json({ error: error instanceof Error ? error.message : '获取文章失败' });
    }
  };

  // 获取文章列表
  getAllPosts = async (req: Request, res: Response): Promise<void> => {
    try {
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 10;
      const publishedOnly = req.query.published === 'true';
      
      const { posts, total } = await this.postService.getAllPosts(page, limit, publishedOnly);
      
      res.json({
        posts,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit),
        },
      });
    } catch (error) {
      res.status(500).json({ error: error instanceof Error ? error.message : '获取文章列表失败' });
    }
  };

  // 获取指定作者的文章
  getPostsByAuthor = async (req: Request, res: Response): Promise<void> => {
    try {
      const { authorId } = req.params;
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 10;
      
      const { posts, total } = await this.postService.getPostsByAuthor(parseInt(authorId), page, limit);
      
      res.json({
        posts,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit),
        },
      });
    } catch (error) {
      res.status(500).json({ error: error instanceof Error ? error.message : '获取作者文章失败' });
    }
  };

  // 更新文章
  updatePost = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const updateData = req.body;
      const authorId = req.body.authorId; // 可选的权限验证
      
      // 移除不允许更新的字段
      delete updateData.id;
      delete updateData.authorId;
      delete updateData.createdAt;
      delete updateData.updatedAt;
      
      const post = await this.postService.updatePost(parseInt(id), updateData, authorId);
      
      if (!post) {
        res.status(404).json({ error: '文章不存在' });
        return;
      }

      res.json({
        message: '文章更新成功',
        post,
      });
    } catch (error) {
      res.status(400).json({ error: error instanceof Error ? error.message : '更新文章失败' });
    }
  };

  // 删除文章
  deletePost = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const authorId = req.body.authorId; // 可选的权限验证
      
      const success = await this.postService.deletePost(parseInt(id), authorId);
      
      if (!success) {
        res.status(404).json({ error: '文章不存在' });
        return;
      }

      res.json({ message: '文章删除成功' });
    } catch (error) {
      res.status(500).json({ error: error instanceof Error ? error.message : '删除文章失败' });
    }
  };

  // 发布文章
  publishPost = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const authorId = req.body.authorId; // 可选的权限验证
      
      const post = await this.postService.publishPost(parseInt(id), authorId);
      
      if (!post) {
        res.status(404).json({ error: '文章不存在' });
        return;
      }

      res.json({
        message: '文章发布成功',
        post,
      });
    } catch (error) {
      res.status(400).json({ error: error instanceof Error ? error.message : '发布文章失败' });
    }
  };

  // 取消发布文章
  unpublishPost = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const authorId = req.body.authorId; // 可选的权限验证
      
      const post = await this.postService.unpublishPost(parseInt(id), authorId);
      
      if (!post) {
        res.status(404).json({ error: '文章不存在' });
        return;
      }

      res.json({
        message: '文章取消发布成功',
        post,
      });
    } catch (error) {
      res.status(400).json({ error: error instanceof Error ? error.message : '取消发布文章失败' });
    }
  };
}